<template>
	<view class="member-payment">
		<view class="member-info-card">
			<view class="member-header">
				<image class="member-icon" src="../../static/01ccc202008191450103239.png" mode=""></image>
				<view class="member-content">
					<view class="member-title">开通VIP会员</view>
					<view class="member-desc">享受专属权益，畅学所有课程</view>
				</view>
			</view>
			<view class="member-benefits">
				<view class="benefit-item">
					<text class="benefit-icon">✓</text>
					<text class="benefit-text">全站课程免费学习</text>
				</view>
				<view class="benefit-item">
					<text class="benefit-icon">✓</text>
					<text class="benefit-text">专属会员标识</text>
				</view>
				<view class="benefit-item">
					<text class="benefit-icon">✓</text>
					<text class="benefit-text">优先客服支持</text>
				</view>
				<view class="benefit-item">
					<text class="benefit-icon">✓</text>
					<text class="benefit-text">一年有效期</text>
				</view>
			</view>
		</view>

		<view class="price-card">
			<view class="price-header">会员价格</view>
			<view class="price-content">
				<view class="price-main">
					<text class="currency">¥</text>
					<text class="amount">100</text>
					<text class="period">/年</text>
				</view>
				<view class="price-desc">开通后立即生效，有效期一年</view>
			</view>
		</view>

		<view class="payment-methods">
			<view class="payment-header">选择支付方式</view>
			<view class="payment-option" @click="selectPayment('weixin')" :class="{'selected': selectedPayment === 'weixin'}">
				<view class="payment-left">
					<image class="payment-icon" src="../../static/weixn-1.png" mode=""></image>
					<text class="payment-name">微信支付</text>
				</view>
				<image class="check-icon" :src="selectedPayment === 'weixin' ? '../../static/xuanzhongsem1.png' : '../../static/weixuanzhongsem1.png'" mode=""></image>
			</view>
			<view class="payment-option" @click="selectPayment('alipay')" :class="{'selected': selectedPayment === 'alipay'}">
				<view class="payment-left">
					<image class="payment-icon" src="../../static/zhifubao-1.png" mode=""></image>
					<text class="payment-name">支付宝支付</text>
				</view>
				<image class="check-icon" :src="selectedPayment === 'alipay' ? '../../static/xuanzhongsem1.png' : '../../static/weixuanzhongsem1.png'" mode=""></image>
			</view>
		</view>

		<view class="payment-footer">
			<view class="total-price">
				<text>总计：</text>
				<text class="total-amount">¥100</text>
			</view>
			<button class="pay-button" @click="createMemberOrder" :disabled="!selectedPayment">
				立即开通会员
			</button>
		</view>
	</view>
</template>

<script>
	import { Request } from '@/utils/request.js'
	
	export default {
		data() {
			return {
				selectedPayment: 'weixin', // 默认选择微信支付
				userinfo: {},
				memberPrice: 100
			}
		},
		onLoad() {
			this.userinfo = JSON.parse(uni.getStorageSync('userinfo') || "{}");
			// 检查用户是否登录
			if (!this.userinfo.uid) {
				uni.showModal({
					title: '提示',
					content: '请先登录',
					showCancel: false,
					success: () => {
						uni.navigateTo({
							url: '/logon/logon/index'
						})
					}
				});
			}
		},
		methods: {
			selectPayment(type) {
				this.selectedPayment = type;
			},
			
			createMemberOrder() {
				if (!this.selectedPayment) {
					uni.showToast({
						title: '请选择支付方式',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({
					title: '创建订单中...'
				});
				
				// 如果是微信支付，先获取微信授权码
				if (this.selectedPayment === 'weixin') {
					// #ifdef MP-WEIXIN
					wx.login({
						success: (loginRes) => {
							if (loginRes.code) {
								// 获取到授权码后调用创建订单接口
								this.callCreateOrderAPI(loginRes.code);
							} else {
								uni.hideLoading();
								uni.showToast({
									title: '获取微信授权失败',
									icon: 'none'
								});
							}
						},
						fail: () => {
							uni.hideLoading();
							uni.showToast({
								title: '微信授权失败',
								icon: 'none'
							});
						}
					});
					// #endif
					
					// #ifndef MP-WEIXIN
					// 非微信小程序环境，直接调用接口
					this.callCreateOrderAPI();
					// #endif
				} else {
					// 其他支付方式，直接调用接口
					this.callCreateOrderAPI();
				}
			},
			
			// 新增方法：调用创建订单API
			callCreateOrderAPI(code = '') {
				// 构建请求参数
				const requestData = {
					payType: this.selectedPayment
				};
				
				// 如果有微信授权码，添加到请求参数中
				if (code) {
					requestData.code = code;
				}
				
				// 调用创建会员订单API
				Request('member/createOrder', requestData, 'post').then((res) => {
					uni.hideLoading();
					
					console.log('支付响应:', res);
					
					if (res.status === 'WECHAT_PAY') {
						// 微信支付
						console.log('开始微信支付:', res.result);
						this.handleWechatPay(res.result);
					} else if (res.status === 'zhifubao_pay') {
						// 支付宝支付
						this.handleAlipayPay(res.result);
					} else if (res.status === 'success') {
						// 支付成功
						this.paymentSuccess();
					} else {
						console.log('未知状态:', res.status);
						uni.showToast({
							title: '支付状态异常',
							icon: 'none'
						});
					}
				}).catch((error) => {
					uni.hideLoading();
					uni.showToast({
						title: error.msg || '创建订单失败',
						icon: 'none'
					});
				});
			},
			
			handleWechatPay(payConfig) {
				// 处理微信支付
				console.log('微信支付配置:', payConfig);
				
				// #ifdef MP-WEIXIN
				const paymentData = {
					'appId': '' + payConfig.jsConfig.appId,
					'timeStamp': '' + payConfig.jsConfig.timestamp,
					'nonceStr': '' + payConfig.jsConfig.nonceStr,
					'package': '' + payConfig.jsConfig.package,
					'signType': "" + payConfig.jsConfig.signType,
					'paySign': '' + payConfig.jsConfig.paySign
				};
				
				console.log('微信支付参数:', paymentData);
				
				wx.requestPayment({
					...paymentData,
					success: (res) => {
						console.log('微信支付成功:', res);
						this.paymentSuccess();
					},
					fail: (err) => {
						console.log('微信支付失败:', err);
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});
					}
				});
				// #endif
				
				// #ifdef H5
				// H5环境下的微信支付处理
				if (typeof WeixinJSBridge !== 'undefined') {
					WeixinJSBridge.invoke('getBrandWCPayRequest', {
						"appId": payConfig.jsConfig.appId,
						"nonceStr": payConfig.jsConfig.nonceStr,
						"package": payConfig.jsConfig.package,
						"signType": payConfig.jsConfig.signType,
						"paySign": payConfig.jsConfig.paySign,
						"timeStamp": payConfig.jsConfig.timestamp
					}, (res) => {
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							this.paymentSuccess();
						}
					});
				}
				// #endif
			},
			
			handleAlipayPay(payConfig) {
				// 处理支付宝支付
				const payInfo = payConfig;
				uni.navigateTo({
					url: `/pages/courseDetails/orderPayment?id=${payInfo.orderId}`
				});
			},
			
			paymentSuccess() {
				uni.showModal({
					title: '恭喜！',
					content: '会员开通成功！',
					showCancel: false,
					success: () => {
						// 跳转到个人中心或首页
						uni.switchTab({
							url: '/pages/home/index'
						});
					}
				});
			}
		}
	}
</script>

<style scoped>
	.member-payment {
		min-height: 100vh;
		background-color: #F7F8FA;
		padding: 20rpx;
	}
	
	.member-info-card {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 20rpx;
		padding: 40rpx;
		margin-bottom: 20rpx;
		color: white;
	}
	
	.member-header {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}
	
	.member-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
		margin-right: 20rpx;
	}
	
	.member-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}
	
	.member-desc {
		font-size: 24rpx;
		opacity: 0.8;
	}
	
	.member-benefits {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}
	
	.benefit-item {
		display: flex;
		align-items: center;
	}
	
	.benefit-icon {
		width: 30rpx;
		height: 30rpx;
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 15rpx;
		font-size: 20rpx;
	}
	
	.benefit-text {
		font-size: 28rpx;
	}
	
	.price-card {
		background: white;
		border-radius: 20rpx;
		padding: 40rpx;
		margin-bottom: 20rpx;
	}
	
	.price-header {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}
	
	.price-main {
		display: flex;
		align-items: baseline;
		margin-bottom: 10rpx;
	}
	
	.currency {
		font-size: 28rpx;
		color: #E26262;
		margin-right: 5rpx;
	}
	
	.amount {
		font-size: 60rpx;
		font-weight: bold;
		color: #E26262;
	}
	
	.period {
		font-size: 24rpx;
		color: #666;
		margin-left: 10rpx;
	}
	
	.price-desc {
		font-size: 24rpx;
		color: #999;
	}
	
	.payment-methods {
		background: white;
		border-radius: 20rpx;
		padding: 40rpx;
		margin-bottom: 20rpx;
	}
	
	.payment-header {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
	}
	
	.payment-option {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.payment-option:last-child {
		border-bottom: none;
	}
	
	.payment-option.selected {
		background-color: #f8f9ff;
		border-radius: 10rpx;
		padding: 30rpx 20rpx;
		margin: 10rpx 0;
	}
	
	.payment-left {
		display: flex;
		align-items: center;
	}
	
	.payment-icon {
		width: 60rpx;
		height: 60rpx;
		margin-right: 20rpx;
	}
	
	.payment-name {
		font-size: 30rpx;
		color: #333;
	}
	
	.check-icon {
		width: 40rpx;
		height: 40rpx;
	}
	
	.payment-footer {
		background: white;
		border-radius: 20rpx;
		padding: 40rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.1);
	}
	
	.total-price {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 30rpx;
		font-size: 32rpx;
	}
	
	.total-amount {
		color: #E26262;
		font-weight: bold;
		font-size: 36rpx;
		margin-left: 10rpx;
	}
	
	.pay-button {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
		border: none;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: bold;
	}
	
	.pay-button:disabled {
		background: #ccc;
	}
</style>